var IssuersModule = function() {
    var editable = function() {

        return {
            init: function() {
            	//手机号码或固定电话验证验证
            	function checkMobile(mobile){ 
            	    if(!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(mobile))&&!(/^0\d{2,3}\d?\d{7,8}\d?/.test(mobile))){ 
            	        return true; 
            	    } 
            	    return false;
            	} 
                //表格初始化
                var oTable = $('#issuersEditable').dataTable({
                    "lengthMenu": [
                        [10, 15, 20, 50],
                        [10, 15, 20, 50]
                    ],
                    "autoWidth": true,
                    "scrollX": true,
                    "displayLength": 10,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "zeroRecords": "数据为空",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info": "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",
                        "infoEmpty": "记录数为0",
                    },
                    "columnDefs": [{
                        "data": null,
                        'sortable': false,
                        "defaultContent": "<center>---<center>",
                        "targets": [7]
                    }],
                    "columns": [{
                        "data": "name",
                        'sortable': false,
                        "defaultContent": ""
                    }, {
                        "data": "contacts",
                        'sortable': false,
                        "defaultContent": ""
                    }, {
                        "data": "contactWay",
                        'sortable': false,
                        "defaultContent": ""
                    }, {
                        "data": "saleCount",
                        'sortable': false,
                        "defaultContent": ""
                    }, {
                        "data": "orgCode",
                        'sortable': false,
                        "defaultContent": "<center>---<center>"
                    }, {
                        "data": "account",
                        'sortable': false,
                        "defaultContent": "<center>---<center>"
                    }, {
                        "data": "disable",
                        'sortable': false,
                        "defaultContent": ""
                    }, ],
                    "filter": false,
                    "processing": false,
                    "serverSide": true,
                    "ajaxSource": ctx + "/issuers/query",
                    "serverMethod": "post",
                    "fnRowCallback": function(nRow, aData, displayIndex) {
                        nRow.children[0].id = aData.id;
                        var disable = "";
                        var operation = ""

                        if (false == aData.disable) {
                            disable = "启用";
                            operation =
                                '<a title="修改" class="update fa fa-pencil-square-o fa-lg pull-left" href="javascript:;"></a>\
                			   &nbsp;<a class="disable fa fa-ban fa-lg pull-left" title="禁用" href="javascript:;"></a>\
                			   &nbsp;<a class="modefiedPassword fa fa-unlock-alt fa-lg pull-left" title="修改密码" href="javascript:;"></a>';
                        } else {
                            disable = "禁用";
                            operation =
                                '<a title="修改" class="update fa fa-pencil-square-o fa-lg pull-left" href="javascript:;"></a>\
                			   &nbsp;<a class="able fa fa-check fa-lg pull-left" title="启用" href="javascript:;"></a>\
                			   &nbsp;<a class="modefiedPassword fa fa-unlock-alt fa-lg pull-left" title="修改密码" href="javascript:;"></a>';
                        }
                        $('td:eq(6)', nRow).html(disable);
                        $('td:eq(7)', nRow).html(operation);
                        return nRow;
                    },
                    "fnServerData": function(ajaxSource, dataSet, fnCallback) {
                        var json = "";
                        var s;
                        for (var i = 0; i < dataSet.length; i++) {
                            s = dataSet[i];
                            if (s.name == 'sEcho') {
                                json = json + '"echo":' + s.value;
                            } else if (s.name == 'iDisplayStart') {
                                json = json + ',"start":' + s.value;
                            } else if (s.name == 'iDisplayLength') {
                                json = json + ',"pageSize":' + s.value;
                            }
                        }
                        var orgId = $("#org_id").attr("value");
                        var form = $("form#queryForm").serializeJSON();
                        var js = form.replace('}', ',');
                        json = js + json + ',"orgId":"' + orgId + '"}';
                        $.ajax({
                            "contentType": "application/json; charset=UTF-8",
                            "dataType": 'json',
                            "type": "POST",
                            "url": ajaxSource,
                            "data": json,
                            "success": fnCallback
                        });
                    },
                });
                jQuery.validator.addMethod("mobileLength", function(value, element) {
                	var flag = !checkMobile(value.trim());
                	return flag;
                }, "联系电话输入有误.");
                
                //添加发行方
                $('#addBtn').click(function() {
                    var modal = $('#addModal').modal('show');
                    var formAdd = $('#addForm');
                    modal.on("hidden.bs.modal", function(e) {
                        $(this).removeData();
                        $("#addForm")[0].reset();
                    });
                   
                    formAdd.validate({
                        focusInvalid: true,
                        rules: {
                            name: {
                                required: true,
                                remote:{
                                	url: ctx + "/issuers/check",
                                    type: "post",
                                    dataType: "json",
                                    data: {type : 1}
                                },
                            },
                            contacts: {
                                required: true,
                            },
                            contactWay: {
                                required: true,
                                mobileLength:true,
                            	number:true,
                            	rangelength:[10,12],
                            },
                            account: {
                                required: true,
                                remote:{
                                	url: ctx + "/issuers/check",
                                    type: "post",
                                    dataType: "json",
                                    data: {type : 2}
                                },
                            },
                            password: {
                                required: true,
                                rangelength: [6, 18]
                            },
                            passwordConfirm: {
                                required: true,
                                rangelength: [6, 18],
                                equalTo: "#password"
                            }
                        },
                        messages: {
                            name: {
                                required: "发行方名称不能为空！",
                                remote:"该发行方名称已被使用",
                            },
                            contacts: {
                                required: "联系人不能为空！"
                            },
                            contactWay: {
                                required: "联系方式不能为空！",
                                number: "请输入合法的联系方式"
                            },
                            account: {
                                required: "账号不能为空！",
                                remote:"该账号已被其他发行方使用",
                            },
                            password: {
                                required: "密码不能为空！"
                            },
                            passwordConfirm: {
                                required: "确认密码不能为空！",
                                equalTo:"两次输入密码不一致"
                            },
                        },
                        success: function(label, element) {
                            var icon = $(element).parent('.input-icon').children('i');
                            $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                            icon.removeClass("fa-warning").addClass("fa-check");
                        },
                        submitHandler: function(form) {
                            var json = $("form#addForm").serializeJSON();
                            $('#addConfirm').attr('disabled', true);
                            $.ajax({
                                type: "post",
                                contentType: "application/json; charset=UTF-8",
                                url: ctx + "/issuers/doAdd",
                                data: json,
                                dataType: "json",
                                success: function(msg) {
                                    if (msg.code == 1) {
                                        bootbox.alert("新增成功！");
                                        modal.modal('hide');
                                        oTable.fnDraw(false);
                                    } else {
                                        bootbox.alert(msg.message);
                                    }
                                    $('#btn_submit').attr('disabled', false);
                                },
                                error: function(msg) {
                                    bootbox.alert(msg.message);
                                    $('#btn_submit').attr('disabled', false);
                                }
                            });
                        }
                    });

                    $('#addConfirm').unbind("click").click(function() {
                        timeout(this, 1);
                        formAdd.submit();
                        $("#addForm")[0].reset();
                    });
                });

                //启用
                $('#issuersEditable').on("click", "a.able", function(e) {
                    e.preventDefault();
                    var obj = $(this);
                    bootbox.confirm("启用此发行方?", function(result) {
                        if (result) {
                            var nRow = obj.parents('tr')[0];
                            var id = nRow.children[0].id;
                            $.ajax({
                                "contentType": "application/json; charset=UTF-8",
                                type: "post",
                                url: ctx + "/issuers/disable",
                                data: "{" + '"id":"' + id + '","disable":"' + false + '"}',
                                dataType: "json",
                                success: function(msg) {
                                    if (msg.code == 1) {
                                        bootbox.alert("状态变为启用");
                                        oTable.fnDraw(false);
                                    } else {
                                        bootbox.alert(msg.message);
                                    }
                                },
                                error: function(msg) {
                                    bootbox.alert(msg.message);
                                }
                            });
                        }
                    });
                });

                //禁用
                $('#issuersEditable').on("click", "a.disable", function(e) {
                    e.preventDefault();
                    var obj = $(this);
                    bootbox.confirm("禁用此发行方?", function(result) {
                        if (result) {
                            var nRow = obj.parents('tr')[0];
                            var id = nRow.children[0].id;
                            $.ajax({
                                "contentType": "application/json; charset=UTF-8",
                                type: "post",
                                url: ctx + "/issuers/disable",
                                data: '{"id":"' + id + '","disable":"' + true + '"}',
                                dataType: "json",
                                success: function(msg) {
                                    if (msg.code == 1) {
                                        bootbox.alert("状态变为禁用");
                                        oTable.fnDraw(false);
                                    } else {
                                        bootbox.alert(msg.message);
                                    }
                                },
                                error: function(msg) {
                                    bootbox.alert(msg.message);
                                }
                            });
                        }
                    });
                });

                //修改
                $('#issuersEditable').on("click", "a.update", (function(e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    var name = $(nRow.children[0]).text();
                    var contacts = $(nRow.children[1]).text();
                    var contactWay = $(nRow.children[2]).text();
                    $('#name').val(name);
                    $('#contacts').val(contacts);
                    $('#contactWay').val(contactWay);

                    var modal = $('#updateModal').modal('show');
                    modal.on("hidden.bs.modal", function(e) {
                        $(this).removeData();
                    });
                    var formUpdate = $('#updateForm');
                    formUpdate.validate({
                        focusInvalid: true,
                        rules: {
                            name: {
                                required: true,
                                remote:{
                                	url: ctx + "/issuers/check",
                                    type: "post",
                                    dataType: "json",
                                    data: {type : 3,"id":id}
                                },
                            },
                            contacts: {
                                required: true,
                            },
                            contactWay: {
                                required: true,
                                mobileLength:true,
                            	number:true,
                            	rangelength:[10,12],
                            },
                        },
                        messages: {
                            name: {
                                required: "发行方名称不能为空！",
                                remote:"该发行方名称已被使用",
                            },
                            contacts: {
                                required: "联系人不能为空！"
                            },
                            contactWay: {
                                required: "联系方式不能为空！",
                                number: "请输入合法的联系方式"
                            },
                        },
                        success: function(label, element) {
                            var icon = $(element).parent('.input-icon').children('i');
                            $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                            icon.removeClass("fa-warning").addClass("fa-check");
                        },
                        submitHandler: function(form) {
                        	var json1 = $("form#updateForm").serializeJSON();
                            var js = json1.replace('}', ',');
                            var json = js + '"id":"' + id + '"}';
                            var modal = $('#updateModal');
                            $.ajax({
                                "contentType": "application/json; charset=UTF-8",
                                type: "post",
                                url: ctx + "/issuers/update",
                                data: json,
                                dataType: "json",
                                success: function(msg) {
                                    if (msg.code == 1) {
                                        bootbox.alert("修改成功！");
                                        modal.modal('hide');
                                        oTable.fnDraw(false);
                                    } else {
                                        bootbox.alert(msg.message);
                                    }
                                },
                                error: function(msg) {
                                    bootbox.alert(msg.message);
                                }
                            });
                        }
                    });
                    $("#updateConfirm").unbind("click").click(function() {
                    	formUpdate.submit();
                    });
                }));
                
                //重置密码
                $('#issuersEditable').on("click", "a.modefiedPassword", (function(e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    var name = $(nRow.children[0]).text();
                    $('#contactName').val(name);

                    var modal = $('#resetModal').modal('show');
                    var formReset = $('#resetForm');
                    modal.on("hidden.bs.modal", function(e) {
                        $(this).removeData();
                        $("#resetForm")[0].reset();
                    });
                    formReset.validate({
                        focusInvalid: true,
                        rules: {
                            password: {
                                required: true,
                                rangelength: [6, 18]
                            },
                            passwordConfirm: {
                                required: true,
                                rangelength: [6, 18],
                                equalTo: "#newPassword"
                            }
                        },
                        messages: {
                            password: {
                                required: "密码不能为空！"
                            },
                            passwordConfirm: {
                                required: "确认密码不能为空！",
                                equalTo:"两次输入密码不一致"
                            },
                        },
                        success: function(label, element) {
                            var icon = $(element).parent('.input-icon').children('i');
                            $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                            icon.removeClass("fa-warning").addClass("fa-check");
                        },
                        submitHandler: function(form) {
                            var js = $("form#resetForm").serializeJSON();
                            $('#resetConfirm').attr('disabled', true);
                            var tmp = js.replace('}',',');
                            var json = tmp+'"id":"'+id+'"}';
                            $.ajax({
                                type: "post",
                                contentType: "application/json; charset=UTF-8",
                                url: ctx + "/issuers/resetPassword",
                                data: json,
                                dataType: "json",
                                success: function(msg) {
                                    if (msg.code == 1) {
                                        bootbox.alert("重置成功！");
                                        modal.modal('hide');
                                    } else {
                                        bootbox.alert(msg.message);
                                    }
                                    $('#resetConfirm').attr('disabled', false);
                                },
                                error: function(msg) {
                                    bootbox.alert(msg.message);
                                    $('#resetConfirm').attr('disabled', false);
                                }
                            });
                        }
                    });

                    $('#resetConfirm').click(function() {
                        timeout(this, 1);
                        formReset.submit();
                    });
                }));

                //查询
                $('#queryBtn').click(function() {
                    oTable.fnClearTable();
                });
            }

        };

    }();

    return {
        init: function() {
            editable.init();
        }
    };
}();